package com.spark.incoicings.utils;


import com.spark.invoicings.entity.Code;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RandomGenerateUtil {
    @Resource
    private RedisTemplate<String,Long> redisTemplate;
    @Resource
    private RedissonClient redissonClient;
    /**
     * 自动编码
     */
    public String nextSerialNumber (Code codeTypeEnum){
        RLock codeNumber = redissonClient.getLock("codeNumber");
        try{
            codeNumber.lock(10, TimeUnit.SECONDS);
            //格式化日期
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(codeTypeEnum.getDateFormat());
            String date = formatter.format(now);
            //获取流水号
            final String TYPE = codeTypeEnum.getType();
            String redisKey = codeTypeEnum.getNumber() + TYPE +":"+date;
            DecimalFormat dft = new DecimalFormat(codeTypeEnum.getSerialFormat());
            Long count = redisTemplate.opsForValue().increment(redisKey,1);
            String code = dft.format(count);
            //组装返回数据
            String format = String.format(codeTypeEnum.getText(), date, code);
            log.info("format={}",format);
            return format;
        }finally{
            codeNumber.unlock();
        }
    }
}